<template>
  <div class="page page-stadium-ticket has-headbar">
		<head-bar :title="this.$route.meta.title" />
		<div class="cover" v-if="cover" :style="{backgroundImage:`url(${cover})`}"></div>
		<ul class="numberList">
  		<li>
				<template v-if="type === 2">
					<p class="timeTitle">选择起始时间</p>
					<van-tabs @click="onTabClick">
						<van-tab :title="item" :key="date" v-for="(item, date) in dayTimes">
							<div class="time-item-box">
                <empty-data text="没有可预约的时间了" :empty="hourData[date].hourPoint.length === 0" :loading="hourData[date].loading"></empty-data>
								<div class="time-item"
                  :class="{on: date == selectDate && seletTimes.findIndex(item => hour == item.hour) !== -1, disabled: hourData[date].totalNum - hourData[date].hourPointValue[hour] <= 0}"
                  v-for="hour in hourData[date].hourPoint"
                  :key="hour" @click="timeSelect(date, hour)">
                  <div>{{hour}}</div><br/>
                  <div>余{{hourData[date].totalNum - hourData[date].hourPointValue[hour]}} &nbsp;&nbsp; {{hourData[date].price[hour]}}¥</div>
                </div>
							</div>
						</van-tab>
					</van-tabs>
				</template>
        <div class="selectTimes">
          <div class="title">{{dayTimes[selectDate]}}</div>
          <div class="time-item on" v-for="(item, index) in seletTimes" :key="index">
            <div>{{item.hour}}</div> <br>
            <div>{{item.price}}¥</div>
          </div>
        </div>
  			<div class="priceOut">
  				<p class="price" v-if="type === 2">{{totalPrice}}<b>￥</b></p>
          <div v-else>票价：<span class="price">{{price}}<b>¥</b></span></div>
  				<div class="stepperOut" v-if="type === 2">
	  				<van-stepper v-model="ticketNumber" @change="numberChange" />
	  				<van-button class="buy-btn" round size="mini" integer type="warning" :disabled="submitDisabled" :loading="submitLoading" @click="orderEvent">预定</van-button>
  				</div>
  			</div>
  		</li>
  	</ul>
  	<div class="ticketInfo">
  		<h3 class="textTitle">预定须知</h3>
  		<div class="html-content" v-html="notice"></div>
  	</div>
  </div>
</template>

<script>
import { Tab, Tabs, Stepper } from 'vant'
import { API_FIELD_DETAIL, API_FIELD_TICKETS, API_BOOKING_ORDER } from '@/service/veneue'
import { certificateMixin, wxjsdkMixin } from '@/components/mixins'
export default {
  name: 'stadium-ticket',
  mixins: [ certificateMixin, wxjsdkMixin ],
  components: {
    [Stepper.name]: Stepper,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs
  },
  data () {
    return {
      cover: '',
      submitLoading: false,
      submitDisabled: false,
      type: 1, // 类型
      dayTimes: {}, // 日期
      hourData: {},
      notice: '',
      ticketNumber: 1,
      price: 0, // 次票价格
      selectDate: null, // 选择的日期
      seletTimes: [] // 选择的时间场次
    }
  },
  computed: {
    itemId () {
      return this.$route.params.id
    },
    totalPrice () {
      let total = 0
      this.seletTimes.forEach((item) => {
        total += parseInt(item.price)
      })
      return total * this.ticketNumber
    }
  },
  mounted () {
    this.wechatHideMenu()
    this.requestTicket().then(() => {
      let shareInfo = {
        title: this.$route.meta.title, // 分享标题
        desc: '',
        link: getWechatLink(window.location.hash), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: this.cover, // 分享图标
        success: function () {
          console.log('分享', getWechatLink(window.location.hash))
        }
      }
      this.wechatShare(shareInfo)
    })
  },
  methods: {
    requestTicket () {
      return API_FIELD_DETAIL({ itemId: this.itemId }).then((resData) => {
        let { type, notice, time } = resData
        this.type = type // 票类型（1次票，2计时票）
        this.notice = notice
        if (type === 1) {
          this.price = resData.price
        } else {
          this.dayTimes = time
          Object.keys(time).forEach((item) => {
            this.$set(this.hourData, item, {
              hourPoint: [],
              hourPointValue: {},
              price: {},
              totalNum: 0,
              status: 0,
              loading: false
            })
          })
          this.requestFieldTickets(Object.keys(time)[0])
        }
      })
    },
    requestFieldTickets (day) {
      this.hourData[day].loading = true
      API_FIELD_TICKETS({ itemId: this.itemId, day: day }).then((resData) => {
        let { hourPoint, hourPointValue, totalNum, price, status } = resData.info
        this.hourData[day].hourPoint = hourPoint
        this.hourData[day].hourPointValue = hourPointValue
        this.hourData[day].totalNum = totalNum
        this.hourData[day].price = price
        this.hourData[day].status = status
      }).finally(() => {
        this.hourData[day].loading = false
      })
    },
    onTabClick (index) {
      //  console.log(Object.keys(this.dayTimes)[index])
      let day = Object.keys(this.dayTimes)[index]
      if (this.hourData[day].hourPoint.length > 0) return
      this.requestFieldTickets(day)
    },
    timeSelect (day, hour) {
      // console.log(this.selectDate, day, hour)
      if (this.hourData[day].totalNum - this.hourData[day].hourPointValue[hour] <= 0) {
        this.$toast('预定已满')
        return
      }
      if (this.selectDate && this.selectDate !== day) {
        this.selectDate = null
        this.seletTimes = []
      }
      this.selectDate = day
      // 再点删除
      let i = this.seletTimes.findIndex(item => item.hour == hour)
      if (i !== -1) {
        this.seletTimes.splice(i, 1)
      }
      // 小于四个加入
      if (this.seletTimes.length < 4) {
        // console.log(this.hourData[day].hourPointValue[hour], this.hourData[day].price[hour])
        if (i === -1) {
          this.seletTimes.push({
            hour,
            num: this.hourData[day].hourPointValue[hour],
            price: this.hourData[day].price[hour]
          })
        }
      }
    },
    // 数量变化
    numberChange (value) {
      let max = Math.max.apply(Math, this.seletTimes.map((item) => item.num))
      // console.log(max)
      if (this.seletTimes.length === 0) {
        this.$toast('请选择时间')
        this.$nextTick(() => {
          this.ticketNumber = 1
        })
      }
      if (this.selectDate && max + this.ticketNumber > this.hourData[this.selectDate].totalNum) {
        this.$toast('数量超过了')
        this.$nextTick(() => {
          this.ticketNumber = this.hourData[this.selectDate].totalNum - max
        })
      }
    },
    orderEvent () {
      this.certificateCheck(true).then(() => {
        this.submitEvent()
      })
    },
    submitEvent () {
      if (!this.selectDate || !this.seletTimes.length) {
        this.$toast('请选择时间')
        return
      }

      this.submitLoading = true
      this.submitDisabled = true
      let reqData = {
        venueID: this.$route.query.venueId,
        itemID: this.itemId,
        number: this.ticketNumber,
        totalPrice: this.totalPrice,
        day: this.selectDate,
        orderTime: this.seletTimes.map((item) => item.hour).join(',')
      }
      // console.log(reqData)
      API_BOOKING_ORDER(reqData).then(resData => {
        this.$router.replace({ name: 'stadium-order', params: { id: resData.info.orderid } })
      }).catch(() => {
        this.submitDisabled = false
      }).finally(() => {
        this.submitLoading = false
      })
    }
  }
}
</script>

<style lang="less">
.page-stadium-ticket{
	width:95%;
	margin: 0 auto;
	@import "../../assets/styles/stadium";
	.cover{
	  width: 100%;
	  height: 200px;
	  background-repeat: no-repeat;
	  background-position: center center;
	  background-size: cover;
	  border-radius: 5px;
	  margin-top:10px;
	}
	.numberList{
		li{
      box-shadow: 0px 0px 17.64px 0.36px rgba(44, 44, 44, 0.09);
      border-radius: 5px;
      margin: 10px 0;
      padding: 5px;
      .name{font-size:18px;margin-top: 10px; margin-bottom:10px;font-weight: bold;}
      .priceOut{
				margin-top: 10px;
      	display: flex;
      	.price{
          color:#FD7B77;
      		font-size:30px;
      		flex: 1;
    			margin-right: 5px;
					b{font-size:13px;}
      	}
				.van-stepper{
					margin-bottom:5px;
				}
				.buy-btn{
					float: right;
					width: 73px;
          height: 25px;
          font-size: 14px;
				}
      }
      .timeTitle{
      	font-size:16px;
      	font-weight:bold;
        margin-bottom: 16px;
      }
		}
	}
	.textTitle{
		border-left:5/2px solid @colorPrimary;
		margin:20px 0 18px;
		text-indent: 5px;
		font-size:16px;
		font-weight: bold;
	}
	@import "../../assets/styles/htmlcontent.less";
	/* tabs */
  .van-tabs--line{
    padding-top: 65/2px;
  }
  .van-tabs--line .van-tabs__wrap{
    height: 60/2px;
  }
  .van-tab{
    background-color: #F7F7F7;
    color: #666666;
    font-size: 12px;
    line-height: 60/2px;
  }
  .van-tab--active{
    background-color: #E3E3E3;
    color: #576ED7;
  }
  .van-tabs__wrap--scrollable .van-tab{
    flex: 0 0 20%;
  }
  .van-tabs__line{display: none;}
  .time-item-box{
    text-align: center;
    border: 1px solid rgba(231,231,231,1);
    padding-top: 10px;
    border-top: none;
  }
  .time-item{
    padding: 4px 10px;
    display:inline-block;
    border-radius: 5px;
    border:1px solid #CBCBCB;
    text-align: center;
    margin: 0 5px 8px 5px;
    font-size: 13px;
    div{
      display: inline-block;
    }
    &.on{
      background:#8EA1F6;
      color:#fff;
      border:1px solid #8EA1F6;
    }
    &.disabled {
      background-color: #bababa;
      color: #fff;
    }
  }
  .selectTimes{
    margin-top: 10px;
    text-align: center;
    .title{
      font-weight: bold;
      font-size:16px;
      margin-bottom: 10px;
    }
  }
}
</style>
